package com.tuanzi.loan.security;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.core.util.IPUtils;
import com.tuanzi.loan.log.entity.LoginLogAction;
import com.tuanzi.loan.log.service.LoginLogService;

@Component
public class LoanAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private SystemUserService userService;
	@Autowired
	private LoginLogService loginLogService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

		String username = request.getParameter("username");
		String contextPath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
		userService.updateLastLoginTimeAndResetRetryTimes(username);
		loginLogService.log(LoginLogAction.LOGIN_SUCCESS, username, IPUtils.getIpAddress(request));

		//如果用默认密码登录，强制用户修改密码
		if(userService.isUseDefaultPassword(username)){
			response.sendRedirect(contextPath + "/views/user-setting.xhtml");
		}else {
			response.sendRedirect(contextPath + "/views/workbench.xhtml");
		}
		
	}

}
